#include "stdafx.h"
#include "leudgrid/TCPSender.h"
#include "leudgrid/TCPRecver.h"
#include "leudgrid/MemoryBlock.h"
#include "leudgrid/StreamBlock.inl"
#include "leudgrid/EventBase.h"
#include "leudgrid/EventQueue.h"
#include "leudgrid/TCPSessionMemoryBlock.h"
namespace LEUD
{
	class senderstream : public LEUD::TCPSenderStream< Stream_t >,public LEUD::PoolMemoryBase< senderstream >{
	public:
		virtual int OnComplete( DWORD Number, DWORD Key );
		virtual int OnFaile( DWORD Error );
	};
	int senderstream::OnComplete( DWORD Number, DWORD Key ){
		m_Stream->Release();
		delete this;
		return 0;
	}
	int senderstream::OnFaile( DWORD Error ){
		m_Stream->Release();
		delete this;
		return 0;
	}

	class recver : public LEUD::TCPRecver<Block_t>,public LEUD::PoolMemoryBase< recver >{
		Stream_t* m_Stream;
		TCPSessionMemoryBlock* m_Session;
	public:
		recver(TCPSessionMemoryBlock* ser);
		virtual ~recver();
	public:
		virtual int OnComplete( DWORD Number, DWORD Key );
		virtual int OnFaile( DWORD Error );
	};
	recver::recver(TCPSessionMemoryBlock* ser):m_Session(ser){
		m_Stream = new Stream_t;
	}
	recver::~recver(){
		delete m_Stream;
	}
	int recver::OnComplete( DWORD Number, DWORD Key ){
		if( Number > 0 ){
			m_Block->size(m_Block->size()+Number);
			(*m_Stream)<<m_Block;
			TCPSessionMemoryBlock* Ser = m_Session;
			Ser->OnRecv(m_Stream);
			Initiate(m_Socket,new Block_t);			
		}else{
			OnFaile(0);
		}
		return 0;
	}
	int recver::OnFaile( DWORD Error ){
		m_Session->OnClose(Error);
		delete m_Block;
		delete this;
		return 0;
	}
	void TCPSessionMemoryBlock::Open( SOCKET sock ){
		LEUD::TCPSession::Open( sock );
		recver* rc = new recver(this);
		rc->Initiate(m_Socket,new Block_t);
	}
	void TCPSessionMemoryBlock::OnClose( DWORD Error ){
		LEUD::TCPSession::OnClose( Error );
	}
	void TCPSessionMemoryBlock::Send( Stream_t* stream ){
		senderstream* ss = new senderstream();
		ss->Initiate(m_Socket,stream);
	}
}
LEUD::PoolMemory<LEUD::senderstream>		LEUD::PoolMemoryBase<LEUD::senderstream>::memPool;
LEUD::PoolMemory<LEUD::recver>				LEUD::PoolMemoryBase<LEUD::recver>::memPool;
